package cn.itcast.n5_共享模型_内存;

import lombok.extern.slf4j.Slf4j;

/**
 * @program: juc
 * @description:
 * @author: flyduck
 * @create: 2024-08-29 15:31
 **/
@Slf4j(topic = "c.Test04_$$$$$_volatile设计模式_优雅停止线程_两阶段终止模式")
public class Test04_$$$$$_volatile设计模式_优雅停止线程_两阶段终止模式 {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination2 twoPhaseTermination2 = new TwoPhaseTermination2();
        twoPhaseTermination2.start();

        Thread.sleep(3500);

        twoPhaseTermination2.stop();
    }
}

@Slf4j(topic = "c.TwoPhaseTermination2")
class TwoPhaseTermination2{

    private Thread monitor;

    private volatile boolean stop = false;

    //启动监控线程
    public void start(){
        monitor = new Thread(() -> {
            while (true) {
                if (stop) {
                   log.debug("料理后事");
                   break;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("执行监控记录");
            }
        });
        monitor.start();
    }

    //停止监控线程
    public void stop(){
        stop = true;
    }

}
